package com.blb.goods_service.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public Boolean buyGoods(){
        //乐观锁，模拟秒杀
        Boolean res = redisTemplate.execute(new SessionCallback<Boolean>() {
            @Override
            public Boolean execute(RedisOperations redisOperations) throws DataAccessException {
                //对goods_num进行监视,乐观锁，其他线程如果修改会失败
                redisOperations.watch("goods_num");
                //获得goods_num
                Integer goodsNum = (Integer) redisOperations.opsForValue().get("goods_num");
                if (goodsNum == 0) {
                    System.out.println("秒杀结束！");
                    return false;
                }
                //启动事务
                redisOperations.multi();
                //数量减一
                redisOperations.opsForValue().increment("goods_num", -1);
                //提交事务
                List list = redisOperations.exec();
                if (list == null || list.size() == 0) {
                    System.out.println("购买失败");
                    return false;
                }
                System.out.println("购买成功" + list.get(0));
                return true;
            }
        });
        return res;
    }

}
